﻿using BarcodeDelay.bean;
using BarcodeDelay.logHelp;
using JTParcrelHelper.bean;
using JTParcrelHelper.MessageClient;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace BarcodeDelay.business
{
    public class LanshouFailGen
    {
        private StreamWriter swb = null;
        FileStream bFile = null;
        ArrayList m_arListWeightBarcodes = new ArrayList();
        public event Action weightEvent;

        public event Action AddMessage;

        public event EventHandler<EargsMessageResult> OnMessageResultEvent;
        private static LanshouFailGen instance;
        public static LanshouFailGen Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new LanshouFailGen();
                }
                return instance;
            }
        }
        private Thread fThreadDep = null;
        public void BeginAnalyThread(ArrayList arListBarCodes, string anayType)
        {
            try
            {
                //initLog();
                m_arListWeightBarcodes.Clear();
                if (fThreadDep != null && (fThreadDep.ThreadState == ThreadState.Running || fThreadDep.ThreadState == ThreadState.Background))
                {
                    fThreadDep.Abort();
                    System.Threading.Thread.Sleep(50);
                }
                if (fThreadDep != null && (fThreadDep.ThreadState == ThreadState.Running || fThreadDep.ThreadState == ThreadState.Background))
                {
                    while (fThreadDep.ThreadState != ThreadState.Aborted)
                    {
                        //当调用Abort方法后，如果thread线程的状态不为Aborted，主线程就一直在这里做循环，直到thread线程的状态变为Aborted为止
                        Thread.Sleep(100);
                    }
                }


                m_arListWeightBarcodes = arListBarCodes;
                fThreadDep = new Thread(new ParameterizedThreadStart(parseLanshouFailBatch));
                fThreadDep.Start((object)arListBarCodes);

                fThreadDep.IsBackground = true;
              

            }
            catch (Exception ex)
            {

            }
        }



        public void parseLanshouFailBatch(object arListBarcodes)
        {
            //htRes = new Hashtable();
            bool lanshouRes = false;
            bool findWeight = false;
            //StoParams.Instance.htResWechat.Clear();
            string resMsg = "";
            int totalDelays = 0;
            int queryServerResTime = 0;
            int priorBarCodeCount = 0;
            ArrayList arListDepResultTmp = new ArrayList();
            try
            {
                
                int totalQueryCount = 0;
                ArrayList arListTmp = new ArrayList();
                RoadInfo roadInfoGen = new bean.RoadInfo();
                Hashtable htRoadMap = new Hashtable();
                ArrayList arListBarCodes = new ArrayList();
                arListBarCodes.Clear();
                DateTime dtStart = System.DateTime.Now;
                int sumQueryTime = 0;
                int avgQueryTime = 2;
                int intProcess = 0;
                string httpRes = "";
                StoParams.Instance.resMsg = "";
                ArrayList arListUseFulBarcodes = new ArrayList();
                bool isCurSiteParcel = false;
                ArrayList arListFails = new ArrayList();
                int failCount = 0;
                intProcess = 0;

                ParcelBean parcelFristBean = new ParcelBean();
                foreach (ParcelBean parcelBean in (ArrayList)arListBarcodes)
                {
                    try
                    {
                        if(parcelFristBean.roomID=="")
                        {
                            parcelFristBean = parcelBean;
                        }
                        
                        string strBarCode = parcelBean.wayBill;
                        intProcess++;
                        ArrayList arListAllGXTask = new ArrayList();
                        string pickName = "";
                        string orderSource = "";
                        string curSiteToken = "";
                        string customerName = "";
                        

                        parcelBean.customerName = customerName;
                        ArrayList arListRoadMap = JTDelayHelper.Instance.getRoadMap(strBarCode, out httpRes, arListAllGXTask);
                        if (!httpRes.Contains("成功"))
                        {
                            failCount++;

                            logHelp.LogHelper.Instance.writeLog(strBarCode + " 请求失败 " + httpRes);
                            StoParams.Instance.resMsg = " 请求失败 " + httpRes;
                            if (AddMessage != null)
                            {
                                AddMessage.Invoke();
                            }
                            System.Threading.Thread.Sleep(100);
                            resMsg = "请求失败";
                            StoParams.Instance.htResWechat[strBarCode] = resMsg;
                            //htRes[strBarCode] = resMsg;
                            continue;
                        }
                        if (httpRes.Contains("成功"))
                        {
                            if(arListRoadMap.Count==0)
                            {
                                StoParams.Instance.htLanshouFail[strBarCode] = "无揽收";
                                arListFails.Add(strBarCode);
                            }
                            continue;
                        }

                        



                    }
                    catch (Exception ex)
                    {

                    }

                }


                if (arListFails.Count > 0)
                {                   
                   
                    if (parcelFristBean.roomID != "")
                    {
                        sendLanshouFailNotice(arListFails, parcelFristBean);
                    }
                    else
                    {
                        EargsMessageResult msg = new EargsMessageResult("lanshouFail", arListFails);
                        this.TriggerMessageReceivedEvent(this, msg);
                    }

                }


                
                if (AddMessage != null&& arListFails.Count==0)
                {
                    StoParams.Instance.resMsg = StoParams.Instance.resMsg+ "  本次揽收校验全部成功";
                    if (failCount== intProcess)
                    {
                        StoParams.Instance.resMsg = "系统查询完毕 "+"系统接口请求失败";
                    }
                    AddMessage.Invoke();
                }
                return;


              





            }
            catch (Exception ex)
            {
                logHelp.LogHelper.Instance.writeLog(" 揽收异常 " + ex.ToString());
            }
            return;


        }



        private void sendLanshouFailNotice(ArrayList arListBarcodes,ParcelBean parcelBean)
        {
            try
            {
                string roomID = parcelBean.roomID;
                string userID = parcelBean.fromWxID;


                StringBuilder sb = new StringBuilder();
                sb.AppendLine("请注意：以下单号揽收失败");
                int curRowCount = 0;
                foreach (string strBarcode in arListBarcodes)
                {
                    sb.AppendLine(strBarcode);
                    curRowCount++;
                    if(curRowCount>=100)
                    {
                        ReplyHelper.Instance.replySuperMsg(roomID, "{$@}" + " " + sb.ToString(), "1", userID);
                        sb.Clear();
                        sb.AppendLine("请注意：以下单号揽收失败");
                        curRowCount = 0;
                    }

                }
               
                if(curRowCount>0)
                {
                    ReplyHelper.Instance.replySuperMsg(roomID, "{$@}" + " " + sb.ToString(), "1", userID);
                }
                
            }
            catch (Exception ex)
            {

            }
        }


        private void TriggerMessageReceivedEvent(object sender, EargsMessageResult args)
        {
            if (this.OnMessageResultEvent != null)
            {
                EventHandlerTrigger.TriggerEvent<EargsMessageResult>(this.OnMessageResultEvent,
                                                 sender, args);
            }
        }

        public void parseLanshou(object arListBarcodes)
        {
            //htRes = new Hashtable();
            bool lanshouRes = false;
            bool findWeight = false;
            //StoParams.Instance.htResWechat.Clear();
            string resMsg = "";
            int totalDelays = 0;
            int queryServerResTime = 0;
            int priorBarCodeCount = 0;
            ArrayList arListDepResultTmp = new ArrayList();
            try
            {
                int totalQueryCount = 0;
                ArrayList arListTmp = new ArrayList();
                RoadInfo roadInfoGen = new bean.RoadInfo();
                Hashtable htRoadMap = new Hashtable();
                ArrayList arListBarCodes = new ArrayList();
                arListBarCodes.Clear();
                DateTime dtStart = System.DateTime.Now;
                int sumQueryTime = 0;
                int avgQueryTime = 2;
                int intProcess = 0;
                string httpRes = "";
                StoParams.Instance.resMsg = "";
                ArrayList arListUseFulBarcodes = new ArrayList();
                foreach (ParcelBean parcelBean in (ArrayList)arListBarcodes)
                {
                    try
                    {
                        string strBarCode = parcelBean.wayBill;
                        intProcess++;
                        ArrayList arListAllGXTask = new ArrayList();
                        string pickName = "";
                        string orderSource = "";
                        string curSiteToken = "";
                        string customerName = "";
                        if (!UtilityHelp.Instance.resetToken(strBarCode, out pickName, out orderSource, out curSiteToken,out customerName))
                        {
                            if (curSiteToken == "")
                            {
                                StoParams.Instance.htResWechat[strBarCode] = " 发件网点 " + pickName + " 登录失效";
                                continue;
                            }

                            System.Threading.Thread.Sleep(50);
                            logHelp.LogHelper.Instance.writeLog(strBarCode + " 发件网点 " + pickName + " 非我司单号  无法处理");
                            StoParams.Instance.htResWechat[strBarCode] = " 发件网点 " + pickName + " 非我司单号  无法处理";
                            continue;

                        }
                        parcelBean.customerName = customerName;
                        ArrayList arListRoadMap = JTDelayHelper.Instance.getRoadMap(strBarCode, out httpRes, arListAllGXTask);
                        if (!httpRes.Contains("成功"))
                        {
                            logHelp.LogHelper.Instance.writeLog(strBarCode + " 请求失败 " + httpRes);
                            StoParams.Instance.resMsg = StoParams.Instance.resMsg + " " + httpRes;
                            System.Threading.Thread.Sleep(100);
                            resMsg = "请求失败";
                            StoParams.Instance.htResWechat[strBarCode] = resMsg;
                            //htRes[strBarCode] = resMsg;
                            continue;
                        }
                        if (httpRes.Contains("成功") && JTDelayHelper.Instance.isLanshouDone(arListRoadMap))
                        {
                            logHelp.LogHelper.Instance.writeLog(strBarCode + " " + "快件已揽收");
                            resMsg = "快件已揽收";
                            StoParams.Instance.htResWechat[strBarCode] = resMsg;
                            //htRes[strBarCode] = "快件已揽收";
                            continue;
                        }
                       
                        arListUseFulBarcodes.Add(parcelBean);



                    }
                    catch(Exception ex)
                    {

                    }                                

                }
                if(arListUseFulBarcodes.Count>0)
                {
                    string laoshouMsg = "";
                    Hashtable htResTmp = new Hashtable();
                    ArrayList arListFails = new ArrayList();

                    ArrayList arListSuccess = new ArrayList();
                    string lanshouMsg = "";
                    lanshouRes = lanshouParcel(arListUseFulBarcodes, out laoshouMsg, htResTmp, arListFails,out lanshouMsg, arListSuccess);
                    foreach (ParcelBean parcelBean in arListUseFulBarcodes)
                    {
                        if(htResTmp.ContainsKey(parcelBean.wayBill))
                        {
                            StoParams.Instance.htResWechat[parcelBean.wayBill] = htResTmp[parcelBean.wayBill].ToString();
                        }                       
                    }
                    StringBuilder sb = new StringBuilder();
                    foreach(string strLine in arListFails)
                    {
                        sb.AppendLine(strLine);
                    }
                    if(sb.ToString().Length>1)
                    {
                        logHelp.LogHelper.Instance.writeLog(" 揽收异常单号 " + sb.ToString());
                    }
                    logHelp.LogHelper.Instance.writeLog("揽收完成 "+ lanshouMsg);

                    Random ran = new Random();
                }
                




            }
            catch (Exception ex)
            {
                logHelp.LogHelper.Instance.writeLog(" 揽收异常 " + ex.ToString());
            }
            return;


        }


        public bool lanshouParcel(ArrayList arListBarcodes, 
            out string msg,Hashtable htResTmp,ArrayList arListFails,out string lanshouMsg,ArrayList arListSuccess)
        {

            lanshouMsg = "揽收成功单号:";
            msg = "";
            bool res = false;
            if(arListBarcodes.Count==0)
            {
                return false;
            }
            try
            {
                //string strUrl = "https://opa.jtexpress.com.cn/opa/smart/scan/uploadReceiptData";
                string strUrl = StoParams.Instance.scanUrl;
                JObject jObj = new JObject();
                int curCount = 0;

                logHelp.LogHelper.Instance.writeLog(" 准备揽收 个数 " + arListBarcodes.Count.ToString());
                if(StoParams.Instance.htLanshouFail.Count>5000)
                {
                    StoParams.Instance.htLanshouFail.Clear();
                }

                foreach (ParcelBean parcelBean in arListBarcodes)
                {
                    try
                    {
                        System.Threading.Thread.Sleep(100);
                        curCount++;
                        //System.Threading.Thread.Sleep(20);
                        string strCurBarcode = parcelBean.wayBill;
                        string weight = parcelBean.weight;
                        jObj["listId"] = System.Guid.NewGuid().ToString().Replace("-", "").ToLower();
                        jObj["billcode"] = strCurBarcode;
                        //jObj["weight"] = Convert.ToDouble(weight);

                        jObj["length"] = 0;
                        jObj["width"] = 0;
                        jObj["height"] = 0;
                        jObj["devicecode"] = "JC0001";
                        jObj["devicename"] = "称重扫描";
                        jObj["imagepath"] = "";
                        string postData = Newtonsoft.Json.JsonConvert.SerializeObject(jObj);
                        string resMsg = HttpClient.HttpUtil.Instance.PostCommonByToken(strUrl, postData, "returnAndForwardMaintain", MemberInfo.Instance.lanshoutoken);
                        logHelp.LogHelper.Instance.writeLog("揽收，返回信息：" + resMsg);
                        string msgCur = "以上单号揽收成功";

                        if(StoParams.Instance.register_site.Contains("曹三")|| StoParams.Instance.register_site.Contains("菊城"))
                        {
                            msgCur = "提前揽收，请贵司核实有无交货哦，当天到件的包裹当天都会有物流更新的呢";
                        }
                        if (!resMsg.Contains("200"))
                        {
                            logHelp.LogHelper.Instance.writeLog("揽收失败，返回信息：" + resMsg);
                            if (resMsg.Contains("无法连接到远程服务器"))
                            {
                                msgCur = "无法连接到远程服务器";
                                StoParams.Instance.htLanshouFail[parcelBean.wayBill] = msgCur;
                                arListFails.Add(parcelBean.wayBill);
                                StoParams.Instance.resMsg = parcelBean.wayBill + " " + "揽收失败 第：" + curCount.ToString() + " 个";
                                if (AddMessage != null)
                                {
                                    AddMessage.Invoke();
                                }
                                htResTmp[parcelBean.wayBill] = msgCur;
                                continue;
                            }
                            JObject jsonObjRes = (JObject)JsonConvert.DeserializeObject(resMsg);
                            JToken codeToken = jsonObjRes["code"];
                            msgCur = UtilityHelp.Instance.getErrorMsg(codeToken.ToString());
                            StoParams.Instance.htLanshouFail[parcelBean.wayBill] = msgCur;
                            arListFails.Add(parcelBean.wayBill);
                            StoParams.Instance.resMsg = parcelBean.wayBill + " " + "揽收失败 第：" + curCount.ToString() + " 个";
                            if (AddMessage != null)
                            {
                                AddMessage.Invoke();
                            }

                        }
                        else
                        {
                            lanshouMsg = lanshouMsg + " " + parcelBean.wayBill;
                            StoParams.Instance.currentBarcode = parcelBean.wayBill;
                            res = true;
                            arListSuccess.Add(parcelBean.wayBill);
                            StoParams.Instance.resMsg = parcelBean.wayBill + " " + "揽收成功 第：" + curCount.ToString() + " 个";
                            if (AddMessage != null)
                            {
                                AddMessage.Invoke();
                            }
                        }
                        htResTmp[parcelBean.wayBill] = msgCur;
                        //htRes[parcelBean.wayBill] = msg;
                    }
                    catch (Exception exe)
                    {
                        logHelp.LogHelper.Instance.writeLog(" 以上单号"+ parcelBean.wayBill + "揽收失败 " + exe.ToString().ToString());
                    }
                    


                }


                /*string postData = Newtonsoft.Json.JsonConvert.SerializeObject(jObj);
                string resMsg = HttpClient.HttpUtil.Instance.PostCommonByToken(strUrl, postData, "returnAndForwardMaintain", MemberInfo.Instance.lanshoutoken);
               
                if (!resMsg.Contains("success"))
                {
                    logHelp.LogHelper.Instance.writeLog("揽收失败，返回信息：" + resMsg);
                    JObject jsonObjRes = (JObject)JsonConvert.DeserializeObject(resMsg);
                    JToken msgToke = jsonObjRes["msg"];
                    msg = "以上单号揽收失败" + msgToke.ToString();
                    return false;
                }
                else
                {
                    msg = "以上单号揽收成功";
                    res = true;
                    return true;
                }*/


                //jsonObjRes = (JObject)JsonConvert.DeserializeObject(resMsg);
            }
            catch (Exception ex)
            {
                logHelp.LogHelper.Instance.writeLog(" 以上单号揽收失败 " + ex.ToString().ToString());
                msg = "以上单号揽收失败" + ex.ToString();
                return false;
            }


            return res;
        }


        private bool autolanshouParcel(ArrayList arListBarcodes,  out string msg)
        {
            msg = "";
            bool res = false;
            try
            {
                string strUrl = "https://opa.jtexpress.com.cn/opa/smart/scan/uploadArrivalCRLSData";
                JObject jObj = new JObject();

                //string listID = System.Guid.NewGuid().ToString().Replace("-", "").ToLower();

                JArray jarry = new JArray();
                foreach(string strCurBarcode in arListBarcodes)
                {
                    jObj["listId"] = System.Guid.NewGuid().ToString().Replace("-", "").ToLower();
                    jObj["arriveScanType"] = "1";
                    jObj["scanTime"] = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    jObj["scanPda"] = "CS0000000001001";
                    jObj["scanTypeCode"] = "91";

                    jObj["weightFlag"] = "2";
                    jObj["waybillId"] = strCurBarcode;
                    jObj["weight"] = "0.3";
                    jarry.Add(jObj);
                }
                
                
                string postData = Newtonsoft.Json.JsonConvert.SerializeObject(jarry);
                string resMsg = HttpClient.HttpUtil.Instance.PostCommonByToken(strUrl, postData, "returnAndForwardMaintain", MemberInfo.Instance.lanshoutoken);
                //string resMsg = HttpClient.HttpUtil.Instance.PostCommonByToken(strUrl, postData, "returnAndForwardMaintain", "7af17dca894c46a8835395dbe45f22f3");
                if (!resMsg.Contains("请求成功"))
                {
                    logHelp.LogHelper.Instance.writeLog("揽收失败，返回信息：" + resMsg);
                    JObject jsonObjRes = (JObject)JsonConvert.DeserializeObject(resMsg);
                    JToken msgToke = jsonObjRes["msg"];
                    msg = "以上单号揽收失败" + msgToke.ToString();
                    return false;
                }
                else
                {
                    msg = "以上单号揽收成功";
                    res = true;
                    return true;
                }


                //jsonObjRes = (JObject)JsonConvert.DeserializeObject(resMsg);
            }
            catch (Exception ex)
            {
                msg = "以上单号揽收失败" + ex.ToString();
                return false;
            }


            return res;
        }







        public void stopThread()
        {
            try
            {
                ArrayList arListT = new ArrayList();
                ResultBean resultBean = new ResultBean();
                if (fThreadDep != null && (fThreadDep.ThreadState == ThreadState.Running || fThreadDep.ThreadState == ThreadState.Background))
                {
                    /*if (totalQueryCount > 0)
                    {
                        resultBean.countTime = totalQueryCount;

                        updateQueryCount(resultBean);
                    }*/
                    fThreadDep.Abort();
                    if (swb != null)
                    {
                        swb.Close();
                    }

                }

    
            }
            catch (Exception ex)
            {

            }
        }


        private void initLog()
        {
            try
            {
                string dir = System.Environment.CurrentDirectory;
                bFile = new FileStream(dir + "\\error.txt", FileMode.Create);
                if (swb == null)
                {
                    swb = new StreamWriter(bFile);
                    swb.WriteLine("begin");

                }
            }
            catch (Exception ex)
            {

            }

        }


    }
}
